<template>
<label :class="{'is-invalid-label': errors.has(name)}">{{ label }}
  <field-error v-show="errors.has(name)" :err="errors.first(name)" />
  <input v-validate="rules"
         :type="type"
         :name="name"
         :class="{'is-invalid-input': errors.has(name)}"
         :placeholder="$t(placeholder)"
         v-model="fieldVal"
         @input="valueChangeHandler"
         :readonly="isReadonly" />
</label>
</template>

<script>
import FieldError from './FieldError';

export default {

  components: {
    FieldError
  },

  props: {
    label: {
      type: String,
      required: true
    },
    type: {
      type: String,
      default: 'text',
      validator(value) {
        return ['text', 'password'].indexOf(value) !== -1;
      }
    },
    placeholder: {
      type: String,
      default: ''
    },
    rules: {
      type: Object,
      default() { return {}; }
    },
    name: {
      type: String,
      required: true
    },
    initVal: {
      type: String
    },
    isReadonly: {
      type: Boolean
    }
  },

  inject: ['$validator'],

  data() {
    return {
      fieldVal: this.initVal
    };
  },

  methods: {

    valueChangeHandler() {
      this.$emit('input', {
        key: this.name,
        val: this.fieldVal
      });
    },

    reset() {
      this.fieldVal = null;
      this.$emit('input', {
        key: this.name,
        val: null
      });
    }

  },

  watch: {
    initVal() {
      this.fieldVal = this.initVal;
    }
  }

};
</script>
